import 'package:bloc/bloc.dart';
import 'package:mobile_app.core/core/domain/entities/learning_content/lexical_item/lexical_item.dart';
import 'package:mobile_app.home.learning.spaced_repetitions/repetition_answer_typing_card/domain/use_cases/apply_hint/use_case.dart';
import 'package:mobile_app.home.learning.spaced_repetitions/repetition_answer_typing_card/domain/use_cases/check_answer/use_case.dart';
import 'package:mobile_app.home.learning.spaced_repetitions/repetition_answer_typing_card/domain/use_cases/get_initial_data/use_case.dart';

part 'bloc_state.dart';

class RepetitionAnswerTypingCardBloc extends Cubit<RepetitionAnswerTypingCardBlocState> {
  RepetitionAnswerTypingCardBloc({
    required LexicalItem lexicalItem,
    required GetInitialData getInitialData,
    required ApplyHint applyHint,
    required CheckAnswer checkAnswer,
  })  : _lexicalItem = lexicalItem,
        _applyHint = applyHint,
        _checkAnswer = checkAnswer,
        super(_getInitialState(
          getInitialData: getInitialData,
        ));

  final LexicalItem _lexicalItem;

  final ApplyHint _applyHint;
  final CheckAnswer _checkAnswer;

  static RepetitionAnswerTypingCardBlocState _getInitialState({
    required GetInitialData getInitialData,
  }) {
    final result = getInitialData();

    return RepetitionAnswerTypingCardBlocState(
      inputText: result.inputText,
    );
  }

  void requestInputTextChange({
    required String inputText,
  }) {
    if (state.inputText == inputText) {
      return;
    }

    emit(state.copyWith(
      inputText: () => inputText,
    ));
  }

  void requestAnswerCheck() {
    final result = _checkAnswer(
      lexicalItemTitle: _lexicalItem.title,
      inputText: state.inputText,
    );

    emit(state.copyWith(
      inputText: () => result.inputText,
      answeredCorrectly: () => result.answeredCorrectly,
      answeredIncorrectly: () => result.answeredIncorrectly,
    ));
  }

  void requestHintApplying() {
    final result = _applyHint(
      lexicalItemTitle: _lexicalItem.title,
      inputText: state.inputText,
    );

    emit(state.copyWith(
      inputText: () => result.inputText,
      hintApplied: () => result.hintApplied,
    ));
  }
}
